package com.myproject.mall.common.util;

import com.myproject.mall.common.constants.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class BloomFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String key = RedisConstants.USER_BLOOM_KEY;
    private final int numHashFunctions = 3; // 使用多个哈希函数减少冲突
    private final long size = 1L << 24; // 约 16MB 大小


    // 添加元素
    public void add(String email) {
        for (int i = 0; i < numHashFunctions; i++) {
            long hash = hash(email, i);
            redisTemplate.opsForValue().setBit(key, Math.abs(hash % size), true);
        }
    }

    // 判断是否存在
    public boolean contains(String phone) {
        for (int i = 0; i < numHashFunctions; i++) {
            long hash = hash(phone, i);
            Boolean exists = redisTemplate.opsForValue().getBit(key, Math.abs(hash % size));
            if (exists == null || !exists) {
                return false;
            }
        }
        return true;
    }

    // 哈希函数（可替换为更复杂的算法）
    private long hash(String s, int seed) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = (seed + s).getBytes(StandardCharsets.UTF_8);
        byte[] digest = md5.digest(bytes);
        long hash = 0;
        for (byte b : digest) {
            hash = (hash << 8) | (b & 0xFF);
        }
        return hash;
    }
}
